package com.example.aop;

import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/*
 * @Author Mr.T
 * @Description  Idempotent注解拦截器
 * @Date  2025/5/11
 **/
@Aspect
@Component
public class IdempotentInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.example.annotion.Idempotent)")
    public void pointHandler(){

    }


    @Before("pointHandler()")
    public void preHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isEmpty(requestAttributes)) {
            throw new RuntimeException("无法获取Http Request");
        }
        //获取对应请求
        HttpServletRequest request = requestAttributes.getRequest();
        //从请求中获取对应token
        String token = request.getHeader("token");
        //尝试从Redis中删除token，如果能够删除成功，则说明该请求是有效请求
        //否则，则是重复请求会被拦截
        if (redisTemplate.delete(token)) {
            //成功删除，则允许通过
            joinPoint.proceed();
        }else{
            throw new RuntimeException("请勿重复提交请求。。。");
        }
    }

}
